package com.sx.shopping.service.goods;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sx.common.util.NumberUtil;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.service.consumer.IMBaseSystemConsumerInfoService;
import com.sx.manage.service.consumer.IMSystemConsumerInfoService;
import com.sx.manage.service.goods.IMGoodsInfoService;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.vo.consumer.MSystemConsumerInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.result.ResultUploadVO;
import com.sx.model.shopping.mybatis.constants.MShoppingConstants;
import com.sx.model.shopping.mybatis.constants.type.GoodsDateType;
import com.sx.model.shopping.mybatis.form.goods.MGoodsInfoForm;
import com.sx.model.shopping.mybatis.vo.goods.MGoodsInfoVO;

/**
 * 商品web程序中service实现类
 * @author lenovo
 *
 */
@Service("goodsRebateInfoWebService")
@Transactional(propagation=Propagation.REQUIRED)
public class MGoodsRebateInfoWebService {
	/*** 日志*/ 
	private Logger _log = LoggerFactory.getLogger(this.getClass());
	@Resource(name="goodsInfoServiceImpl")
	private IMGoodsInfoService goodsInfoServiceImpl;

	//系统用户service
	@Resource(name="systemConsumerInfoServiceImpl")
	private IMSystemConsumerInfoService systemConsumerInfoServiceImpl;
	
	//系统用户service
	@Resource(name="mBaseSystemConsumerInfoServiceImpl")
	private IMBaseSystemConsumerInfoService mBaseSystemConsumerInfoServiceImpl;
	
	/** 1增加数据  */ 
	public ResultBooleanVO  saveAndIssue( MGoodsInfoForm  form, MConsumerLoginVO  loginConsumer){
		_log.debug("首选增加商品(保存并发布)："+JackJsonUtil.objToJson(form));
 		if( null == form){
 			return new ResultBooleanVO("m.parameter.is.null");
 		}
		form.setState(MSystemConstants.ONLINE);
		return save(form,loginConsumer);
	}
	/** 1增加数据  */ 
	public ResultBooleanVO  save( MGoodsInfoForm  form, MConsumerLoginVO  loginConsumer){
		_log.debug("首选增加商品（保存）："+JackJsonUtil.objToJson(form));
		
		ResultBooleanVO result = this.validateForm(form);
		if( !result.isSuccess()){
			return result;
		}
		
		form.setData_type(GoodsDateType.DATA_COMMING_REBATE_PRODUCT);
		if( null == form.getState()){
			form.setState(MSystemConstants.OFFLINE);
		}		
		form.setCreate_time( new Date());
		form.setConsumer_id( loginConsumer.getConsumer_id());
		
		
		 ResultObjectVO<MGoodsInfoForm> formResult = goodsInfoServiceImpl.save(form, loginConsumer); 
		if( !formResult.isSuccess()){
			_log.debug("添加商品出错返回："+formResult.getMsg());
			return new ResultBooleanVO(false,null,formResult.getMsg());
		}
		_log.debug("添加商品完成");
		return result;
	}
	
	private ResultBooleanVO validateForm(MGoodsInfoForm  form){
		//查询数据是否存在 状态如何
		
				if (null != form.getId()) {
							ResultObjectVO<MGoodsInfoVO> vo = goodsInfoServiceImpl.queryById(form.getId());
							MGoodsInfoVO mvo = vo.getObjVo();
							if (null != mvo && mvo.getState().equals(MSystemConstants.ONLINE)) {
									_log.error("请将商品下架，再商品信息！");
										return new ResultBooleanVO(false, null, "请将商品下架，再修改商品信息！");
							}
				}
			return new 	ResultBooleanVO();
	}
	
	
	/** 4根据id查询数据*/ 
	public ResultObjectVO<MGoodsInfoVO> queryById(Long id){ 
		
		
		ResultObjectVO<MGoodsInfoVO> result =  this.goodsInfoServiceImpl.queryById(id);
		_log.debug("查询发布对象，操作人等数据");
		this.searchConsumerAndBusiness(result.getObjVo(),true);
			
		return result;
	}
	
	
	/** 5查询分页*/ 
	public ResultListVO<MGoodsInfoVO>  queryPage( MGoodsInfoForm  form ){ 
		
		form.setData_type( GoodsDateType.DATA_COMMING_REBATE_PRODUCT);
		ResultListVO<MGoodsInfoVO> result =  this.goodsInfoServiceImpl.queryPage(form);
		_log.debug("查询发布对象，操作人等数据");
		this.searchConsumerAndBusiness(result.getData(),false);
		return result;
	}
	
	
	/** 6 商品上架 */ 
	public ResultBooleanVO  onLine(Long[] ids, MConsumerLoginVO  loginConsumer ){ 
		_log.debug("商品商家ids="+NumberUtil.arrayToStr(ids));
		return this.goodsInfoServiceImpl.editStatus(MShoppingConstants.GOODS_ON_LINE, ids,loginConsumer);
	} 
	
	/** 6.1 商品下架 */ 
	public ResultBooleanVO  offLine(Long[] ids , MConsumerLoginVO  loginConsumer){ 
		_log.debug("商品下架ids="+NumberUtil.arrayToStr(ids));
		return this.goodsInfoServiceImpl.editStatus(MShoppingConstants.GOODS_OFF_LINE, ids,loginConsumer);
	} 
	/** 7查询数据集合 */ 
	public ResultListVO<MGoodsInfoVO>  queryList( MGoodsInfoForm  form){ 
		_log.debug("查询数据列表");
		return this.goodsInfoServiceImpl.queryList(form);
	}
	/*** 11 图片上传 流程*/
	@RequestMapping(value = "/upload")
	@ResponseBody
	public ResultUploadVO upload(@RequestParam(value = "files", required = false) MultipartFile file, HttpServletRequest request, MConsumerLoginVO  loginConsumer) { 
		String paths = null;
		String path = request.getSession().getServletContext().getRealPath("upload");  
		 String fileName = file.getOriginalFilename();  
		File targetFile = new File(path, fileName);  
		if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
//		try {
//			file.transferTo(targetFile);
//			paths =  OSSUtils.uploadFile(targetFile, MSystemConstants.SYS_UPLOAD_URL_);
//			targetFile.delete();
//			if (null == paths) {
//				return new ResultUploadVO("sj.m.common.upload.error");
//			}
//			_log.info("上传文件成功，路径 :"+paths);
//		} catch (IllegalStateException e1) {
//			e1.printStackTrace();
//		} catch (IOException e1) {
//			e1.printStackTrace();
//		} catch (OSSException e) {
//			e.printStackTrace();
//		} catch (ClientException e) {
//			e.printStackTrace();
//		} 
		ResultUploadVO result = new ResultUploadVO();
		result.setSuccess(true);
		result.setMsgcode("sj.m.common.upload.success");
		result.setPath(paths);
		return result;
	}  
	/** 12 取消***/
	public ResultBooleanVO cancel(String sku_id, MConsumerLoginVO  loginConsumer){ 
		if( StringUtils.isBlank( sku_id )){
			return new ResultBooleanVO("m.parameter.is.null");
		}
		return new ResultBooleanVO();
	}
	/** 商品集合查询发布对象等数据**/
	public void searchConsumerAndBusiness(List<MGoodsInfoVO> voList,Boolean searchChannels ){
		if( null != voList && !voList.isEmpty()){
			for( MGoodsInfoVO vo:voList){
				searchConsumerAndBusiness(vo,searchChannels);
			}
		}
	}
	/** 单个商品查询发布对象等数据**/
	public void searchConsumerAndBusiness(MGoodsInfoVO vo_,Boolean searchChannels){

		if( null !=  vo_){					
			//查询操作人
			if( null != vo_.getConsumer_id()){
				//_log.debug("查询商品操作人 consumer_id="+vo_.getConsumer_id());
				ResultObjectVO<MSystemConsumerInfoVO> result = this.mBaseSystemConsumerInfoServiceImpl.queryById( vo_.getConsumer_id() );
				if( null!= result &&  null !=result.getObjVo()){
					vo_.setConsumer_name( result.getObjVo().getConsumer_name());
				}
			}						
		}//end if vo_
	}
}
